package com.sgx.learning.luban.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioSelectorServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        serverSocket.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器启动成功");

        while(true) {
            //阻塞等待要处理的事件
            int select = selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if(key.isAcceptable()) {
                    ServerSocketChannel socket = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = socket.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    System.out.println("客户端连接成功");
                } else if(key.isReadable()) {
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer b = ByteBuffer.allocate(128);
                    int read = channel.read(b);
                    if(read > 0) {
                        System.out.println("接收到客户端数据:" + new String(b.array(),0,read));
                    } else if(read == -1) {
                        channel.close();
                        System.out.println("断开连接");
                    }
                }
                iterator.remove();
            }
        }
    }
}
